package com.ruoyi.framework.config.jdbc;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Component
class MetaHandler implements MetaObjectHandler {

    public static final String COMMON_FIELD_CREATETIME = "createTime";
    public static final String COMMON_FIELD_CREATEBY = "createBy";

    public static final String COMMON_FIELD_UPDATETIME = "updateTime";
    public static final String COMMON_FIELD_UPDATEBY = "updateBy";

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser userEntity = SecurityUtils.getLoginUser();
//        Object fieldValue = getFieldValByName(COMMON_FIELD_CREATETIME, metaObject);
//        if (fieldValue != null) {
        if (userEntity != null) {
            this.strictInsertFill(metaObject, COMMON_FIELD_CREATEBY, userEntity::getUsername, String.class);
            this.strictInsertFill(metaObject, COMMON_FIELD_UPDATEBY, userEntity::getUsername, String.class);
        }
        this.strictInsertFill(metaObject, COMMON_FIELD_CREATETIME, LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, COMMON_FIELD_UPDATETIME, LocalDateTime::now, LocalDateTime.class);
//        }

    }


    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser userEntity = SecurityUtils.getLoginUser();
//        Object fieldValue = getFieldValByName(COMMON_FIELD_UPDATETIME, metaObject);
//        if (fieldValue != null) {
        if (userEntity != null) {
            this.strictUpdateFill(metaObject, COMMON_FIELD_UPDATEBY, userEntity::getUsername, String.class);
        }
        this.strictUpdateFill(metaObject, COMMON_FIELD_UPDATETIME, LocalDateTime::now, LocalDateTime.class);
//        }


    }

}
